﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using AutofacAopDemo.Terminal.Interceptors;
using AutofacAopDemo.Terminal.Models;
using AutofacAopDemo.Terminal.Services;

https://blog.ivankahl.com/introduction-to-aspect-oriented-programming-in-dotnet-with-autofac-interceptors/

var container = BuildContainer();

// Create a lifetime scope which we can use to resolve services
// https://autofac.readthedocs.io/en/latest/resolve/index.html#resolving-services
using var scope = container.BeginLifetimeScope();

var labelMaker = scope.Resolve<ILabelMaker>();

// Prompt the user for label contents
Console.Write("Please enter label contents: ");
var contents = Console.ReadLine();

// Output dimensions
var dimensions = labelMaker.CalculateLabelSize(contents);
Console.WriteLine($"Label size will be: {dimensions.width} x {dimensions.height}");

// Print the label
labelMaker.Print(contents);

/// <summary>
/// Builds an Autofac container with the necessary services.
/// </summary>
/// <returns>
/// Autofac container that can be used to resolve services.
/// </returns>
static IContainer BuildContainer()
{
    var builder = new ContainerBuilder();

    // First register our interceptors
    builder.RegisterType<CustomLoggingInterceptor>();

    builder.RegisterType<DbContext>()
        .As<IDbContext>()
        .SingleInstance();

    // Register our label maker service as a singleton
    // (so we only create a single instance)
    builder.RegisterType<ConsoleLabelMaker>()
        .As<ILabelMaker>()
        .SingleInstance()
        .EnableInterfaceInterceptors()
        .InterceptedBy(typeof(CustomLoggingInterceptor));

    return builder.Build();
}